package com.yb.rxjava.interval;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;

import com.yb.rxjava.databinding.ActivityIntervalBinding;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class IntervalActivity extends AppCompatActivity {

    private static final String TAG = IntervalActivity.class.getSimpleName();

    private ActivityIntervalBinding intervalBinding;

    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intervalBinding = ActivityIntervalBinding.inflate(LayoutInflater.from(this));
        setContentView(intervalBinding.getRoot());
        intervalBinding.mBtInterval.setOnClickListener(v -> {
            disposable = Observable.interval(2, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(aLong -> {
                        Log.e(TAG, "------>" + (aLong++));
                        intervalBinding.mTvIntervalResult.setText(String.valueOf(aLong++));
                    });
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}